﻿#include "titlebar.h"
#include "ui_titlebar.h"


TitleBar::TitleBar(QWidget *parent, QString title) :
    QWidget(parent),
    ui(new Ui::TitleBar)
{
    ui->setupUi(this);
    this->setTitle(title);

    isMax = false;
    scaleAnimation = new QPropertyAnimation(this->window(), "geometry");
    scaleAnimation->setEasingCurve(QEasingCurve::InOutQuart);
    scaleAnimation->setDuration(200);


    //标题栏上三个按钮的功能
    connect(ui->Close, &QPushButton::clicked,[this]{
        this->window()->close();
    });
    connect(ui->Min, &QPushButton::clicked,[this]{
        this->window()->showMinimized();
    });
    connect(ui->Max, &QPushButton::clicked, this, &TitleBar::maxButtonClicked);
}

TitleBar::~TitleBar()
{
    delete ui;
}

void TitleBar::setTitle(QString title){
    ui->Title->setText(title);
}

//双击标题栏可以最大化/还原
void TitleBar::mouseDoubleClickEvent(QMouseEvent *event){
    Q_UNUSED(event);
    ui->Max->clicked();
}

//重载系列鼠标事件让标题被拖动时可以改变位置，参考豆子 https://tinyurl.com/r75bmk2
void TitleBar::mousePressEvent(QMouseEvent *event){
    clickPos = mapToParent(event->pos());
}

//重载拖动事件
void TitleBar::mouseMoveEvent(QMouseEvent *event){
    //最大化状态下禁止拖动
    if (isMax){
        return;
    }
    parentWidget()->move(event->globalPos() - clickPos);
}

void TitleBar::maxButtonClicked(){
    if(isMax){
        isMax = false;
        ui->Max->setIcon(QIcon(":/icon/max.svg"));
        scaleAnimation->setStartValue(this->window()->geometry());
        scaleAnimation->setEndValue(lastGeometry);
        scaleAnimation->start();
    }
    else
    {
        isMax = true;
        ui->Max->setIcon(QIcon(":/icon/restore.svg"));
        lastGeometry = this->window()->geometry();
        scaleAnimation->setStartValue(lastGeometry);
        scaleAnimation->setEndValue(this->window()->screen()->availableGeometry());
        scaleAnimation->start();
    }
}
